package mysql

import (
	"gorm.io/gorm"
	"manuscriptservice/manuscriptservicerpc/manuscriptservicerpc"
)

type Good struct {
	gorm.Model
	Title   string `gorm:"type:varchar(50);not null;"`
	Time    string `gorm:"type:varchar(50);not null;"`
	Image   string `gorm:"type:varchar(50);not null;"`
	Stock   int64  `gorm:"type:int(11);not null;"`
	ClassId int64  `gorm:"type:int(11);not null;"`
}

func (g *Good) ManuAdd(db *gorm.DB) error {
	return db.Debug().Create(g).Error
}

func (g *Good) FindManuList(db *gorm.DB, title string) error {
	return db.Debug().Where("title = ?", title).Find(g).Error
}

// SELECT
//
// *
// FROM
//
// goods
//
// LEFT JOIN classes ON goods.class_id = classes.id
func ManuList(db *gorm.DB, list []*manuscriptservicerpc.ManuList, in *manuscriptservicerpc.ListRequest) []*manuscriptservicerpc.ManuList {
	db.Debug().Model(&Good{}).Select(
		"goods.id as manu_id",
		"title",
		"time",
		"image",
		"stock",
		"classes_id as class_id",
	).Joins("LEFT JOIN classes ON goods.class_id = classes.id").
		Find(&list).Scopes(Paginate(int(in.Page), int(in.Size)))
	return list
}

func Paginate(page int, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
